package com.zyz.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyz.common.core.constants.CacheConstants;
import com.zyz.common.redis.service.RedisService;
import com.zyz.friend.mapper.user.UserMapper;
import com.zyz.friend.model.user.User;
import com.zyz.friend.model.user.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class UserCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;

    public UserVO getUserById(Long userId) {
        String userKey = getUserKey(userId);
        // 通过redis拿到用户详情
        UserVO userVO = redisService.getCacheObject(userKey, UserVO.class);
        if (userVO != null) {
            // 设置有效期10分钟
            redisService.expire(userKey, 10, TimeUnit.MINUTES);
            return userVO;
        }
        // 从数据库中查询
        User userByDB = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,
                        User::getNickName,
                        User::getHeadImage,
                        User::getGender,
                        User::getPhone,
                        User::getEmail,
                        User::getWechat,
                        User::getSchoolName,
                        User::getMajorName,
                        User::getIntroduce,
                        User::getStatus)
                .eq(User::getUserId, userId));
        log.info("userDB:{}", userByDB);
        if (userByDB == null) {
            return null;
        }
        // 刷新redis中的缓存
        refreshUser(userByDB);
        // 转换UserVO数据
        return BeanUtil.copyProperties(userByDB, UserVO.class);
    }

    public void refreshUser(User user) {
        String userKey = getUserKey(user.getUserId());
        redisService.setCacheObject(userKey, user);
        // 设置有效期10分钟
        redisService.expire(userKey, 10, TimeUnit.MINUTES);
    }

    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }


}
